import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings
import json

class ContractChangeNewResource(BaseResource):
    def get(self):
        result = models.ContractChange.get_id()
        return result[0]

    @require_admin_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))
        contractchange = models.ContractChange(
        id=req["id"],
        org=self.current_org,
        userid=req["userid"],
        bill_date = req["bill_date"],
        contractsid = req["contractsid"],
        employeeid=req["employeeid"],
        departmentid=req["departmentid"],
        code=req["code"],
        contractcode=req["contractcode"],
        name=req["name"],
        type=req["type"],
        party_aid=req["party_aid"],
        party_bid=req["party_bid"],
        party_cid=req["party_cid"],
        pay_direction=req["pay_direction"],
        pricetype =req["pricetype"],
        sign_date=req["sign_date"],
        start_date=req["start_date"],
        end_date=req["end_date"],
        amount=req["amount"],
        amount_words=req["amount_words"],
        status=req["status"],
        message=req["message"],
        officialcode=req["officialcode"],
        budgetcode=req["budgetcode"],
        templateid=req["templateid"],
        templatecontent=req["templatecontent"],
        changebefore=json.dumps(req["changebefore"]),
        sourcetype=req["sourcetype"],
        sourceid=req["sourceid"],
        contractsealid=0,
        contractrecordid=0,
        billstatusid=0,
        typeid=0,
        workflow_state=0,
        amounttype=req["amounttype"],
        infrastructure=req["infrastructure"],
        recordcode=req["recordcode"],
        puremployeeid=req["puremployeeid"],
        warn_date=req["warn_date"],
        contracttype=req["contracttype"],
        zhengcai=req["zhengcai"],
        isbulu=req["isbulu"],
        warn_message=req["warn_message"],
        warn_check=req["warn_check"],
        volumepurchase=req["volumepurchase"],
        warn_checkdate=req["warn_checkdate"],
        iskeyan=req["iskeyan"],
        iszhaobiao=req["iszhaobiao"],
        empowersex=req["empowersex"],
        empowerduties=req["empowerduties"],
        agreementcount=req["agreementcount"],
        empowerperson=req["empowerperson"],
        warnsealuser=req["warnsealuser"],
        )
        contractactivity = models.ContractActivity(
        userid=req["userid"],
        contractsid = req["contractsid"],
        message ="合同变更",
        sourcetype ="contractchange",
        sourceid =req["id"],
        )
        try:
            models.db.session.add(contractchange)
            models.db.session.add(contractactivity)
            strsql="""insert into attaches(userid,type,annex,status,updated_at,created_at,sourcetype,sourceid,org_id)
            select userid,'contractchange',annex,status,updated_at,created_at,'contractchange',"""+str(req["id"])+""",org_id from attaches
            where sourcetype='contracts' and sourceid="""+str(req["contractsid"])
            models.db.session.execute(strsql)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)


class ContractChangeResource(BaseResource):
    def get(self, contractchange_id):
        result = models.ContractChange.get_by_id(contractchange_id)
        return result.to_dict()

    @require_admin_default
    def post(self, contractchange_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        contractchange = models.ContractChange.get_by_id(contractchange_id)
        params = dict(bill_date=req["bill_date"], employeeid=req["employeeid"], departmentid=req["departmentid"], code=req["code"],
                name=req["name"],type=req["type"],party_aid=req["party_aid"],party_bid=req["party_bid"],party_cid=req["party_cid"],pricetype =req["pricetype"],
                pay_direction=req["pay_direction"],sign_date=req["sign_date"],start_date=req["start_date"],end_date=req["end_date"],amount=req["amount"],
                officialcode=req["officialcode"],budgetcode =req["budgetcode"], templateid=req["templateid"], templatecontent=req["templatecontent"],
                amount_words=req["amount_words"],contractcode=req["contractcode"],message=req["message"],changebefore=json.dumps(req["changebefore"]),
                amounttype=req["amounttype"],infrastructure=req["infrastructure"],recordcode=req["recordcode"],puremployeeid=req["puremployeeid"],
                warn_date=req["warn_date"],contracttype=req["contracttype"],zhengcai=req["zhengcai"],isbulu=req["isbulu"],warn_message=req["warn_message"],
                warn_check=req["warn_check"],volumepurchase=req["volumepurchase"],warn_checkdate=req["warn_checkdate"],iskeyan=req["iskeyan"],
                iszhaobiao=req["iszhaobiao"],empowersex=req["empowersex"],empowerduties=req["empowerduties"],
                agreementcount=req["agreementcount"],empowerperson=req["empowerperson"],warnsealuser=req["warnsealuser"])
        try:
            self.update_model(contractchange, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

class ContractChangedeleteResource(BaseResource):
    @require_admin_default
    def post(self, contractchange_id):
        contractchange =  models.ContractChange.get_by_id(contractchange_id)
        contractactivity = models.ContractActivity.get_by_sourceid("contractchange",contractchange_id)
        models.db.session.delete(contractchange)
        models.db.session.delete(contractactivity)
        models.db.session.commit()

class ContractChangeListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        code = req["code"]
        name = req["name"]
        contractcode = req["contractcode"]
        contractname = req["contractname"]
        type = req["type"]
        userid = str(req["userid"])
        orderfield = req["field"] if "field" in req else ""
        if orderfield=="code" :
            orderfield ="t1.code"
        elif orderfield=="contractcode":
            orderfield ="t1.contractcode"
        elif orderfield=="name":
            orderfield ="t1.name"
        elif orderfield=="partyaname":
            orderfield ="t3.strcustomername"
        elif orderfield=="typename":
            orderfield ="t4.typename"
        elif orderfield=="amount":
            orderfield ="t1.amount"
        else:
            orderfield ="t1.id"
        order = req["order"] if "order" in req else 0

        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !="" :
            strwhere = strwhere + " and t1.code like '%"+code+"%'"
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"
        if contractcode !='' :
            strwhere = strwhere + " and t2.code like '%"+contractcode+"%'"
        if contractname !='' :
            strwhere = strwhere + " and t2.name like '%"+contractname+"%'"
        if type !='' :
            strwhere = strwhere + " and  '"+type+"' = ANY(t2.type)"
        if userid !='':
            strwhere = strwhere + """ and  exists(select orgpower_ids from public.users where id='""" + userid + """' 
            and (t1.departmentid=any(orgpower_ids) or 0=any(orgpower_ids)))"""

        strgetfield =""" t1.*,t2.code as contractcodeold,t2.name  as contractname,
                    t3.strcustomername as partyaname,t4.typename,
                    case when t1.status=2 then '已审核' when t1.status=1 then '审核中' else '草稿' end strstatus"""

        tblname = """public.contractchange t1 inner join public.contracts t2 on t1.contractsid=t2.id
                 left join public.customertemp t3 on t1.party_aid=t3.id  left join
                    public.contracttypeview t4 on t1.type =t4.type  and t1.org_id=t4.org_id"""
        #orderfield ="t1.id"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
        return result[0]
